<template>
  <div class="resetpassword-form">
    <span class="resetpassword-phone">重置密码</span>
    <div class="error-tips">
        <span v-show="validateError" class="valid-error-tips"><i class="error-face">
          <img src="../../assets/svg/error-tips.svg" alt=""></i>
          {{str}}
        </span>
    </div>
    <input-com class="input-block" type="text" label="手机号" :maxLength="11" @result="phoneVal"></input-com>
    <input-com class="input-block" type="text" label="验证码" :maxLength="4" @result="validateVal"></input-com>
    <div class="input-block flex">
      <span v-show="!loadingCaptcha" class="captcha-wrap" ref="captchaWrap"></span>
      <span v-if="loadingCaptcha" class="captcha-load flex">验证码加载中...</span>
      <span class="captcha-wrap layer" v-tap="{methods:verificaPhone}" v-if="phone ===''? true: false"></span>
    </div>
    <input-com class="input-block" type="password" label="密码" :maxLength="20" @result="passwordVal"></input-com>
    <input-com class="input-block" type="password" label="确认密码" :maxLength="20" @result="conformVal"></input-com>
    <button class="resetPassWord-submit text-center" v-tap="{methods:reset}">提交</button>
  </div>
</template>
<script>
  import request from '../../../api/request'
  import InputCom from '../../components/input/input-plugin'
  // 引入验证框配置
  require('../../plugins/captcha/gt.js')
  export default {
    name: 'password',
    data () {
      return {
        captchaObj: null,
        cert: null,
        validateError: false,
        str: '',
        phone: '',
        validate: '',
        password: '',
        conform: '',
        loadingCaptcha: true,
        validToken: ''
      }
    },
    created () {
      this.initCaptcha()
    },
    components: {
      InputCom
    },
    methods: {
      // 初始认证码
      initCaptcha () {
        let params = {
          t: Date.now()
        }
        request.get('verificationCode', params).then(response => {
          let data = response.data
          this.validToken = data.data.neican_token
          let options = {
            // 以下 4 个配置参数为必须，不能缺少
            gt: data.data.gt,
            challenge: data.data.challenge,
            offline: !data.data.success, // 表示用户后台检测极验服务器是否宕机
            new_captcha: data.data.new_captcha, // 用于宕机时表示是新验证码的宕机

            product: 'float', // 产品形式，包括：float，popup
            width: '100%',
            height: '46px'
            // 更多配置参数说明请参见：http://docs.geetest.com/install/client/web-front/
          }
          // 调用 initGeetest 进行初始化
          // 参数1：配置参数
          // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它调用相应的接口
          initGeetest(options, this.validateHandler)
        }).catch(error => {
          throw new Error('fetch captcha pre_valid error: ' + error)
        })
      },
      // 认证码加载handler
      validateHandler (captchaObj) {
        let captchaDom = this.$refs.captchaWrap
        captchaObj.appendTo(captchaDom)
        captchaObj.onReady(() => {
          this.loadingCaptcha = false
          this.captchaObj = captchaObj
          try {
            let timer = setInterval(() => {
              let result = captchaObj.getValidate()
              if (result) {
                this.submitValid()
                clearInterval(timer)
              }
            }, 100)
          } catch (error) {
            throw new Error('validate captcha error: ' + error)
          }
        })
      },
      // 提交滑动认证码
      submitValid () {
        var result = this.captchaObj.getValidate()
        if (!result) {
          return alert('请完成验证')
        }

        let params = {
          geetest_challenge: result.geetest_challenge,
          geetest_validate: result.geetest_validate,
          geetest_seccode: result.geetest_seccode,
          neican_token: this.validToken
        }

        // use form data
        let fd = this.genFormData(params)
        // request.headers()
        request.formDataPost('sendValid', fd).then(response => {
          if (response.data.code !== '200') {
            this.hasError = true
            this.errorTip = '滑动验证码验证错误，请刷新重试'
            captchaObj.reset()
            return
          }
          let data = response.data.data
          this.cert = data.cert
          this.reqPhoneCaptcha()
        }, error => {
          throw new Error('post valid captcha error: ' + error)
        })
      },
      // 打包数据称form-data格式
      genFormData (params) {
        let fd = new FormData()
        for (let x in params) {
          fd.append(x, params[x])
        }
        return fd
      },
      // 请求手机验证码
      reqPhoneCaptcha () {
        let { phone, cert } = this
        // 电话号码校验
        // if (phoneNumber.valid) {
        //   // 手机号码格式不对
        //   // 拒绝发射验证码req
        //   return
        // }
        let params = {
          phone: phone,
          cert
        }
        let fd = this.genFormData(params)
        request.formDataPost('sendMessage', fd).then(response => {
          if (response.code !== '200') {
            this.hasError = true
            this.errorTip = '验证码发送失败，请刷新重新发送'
          }
        }).catch(error => {
          throw new Error('send msg error: ' + error)
        })
      },
      reset () {
        const me = this
        let valData = [
          {
            regex: 'phone',
            message: '手机号码不能为空或者格式不正确',
            data: me.phone
          },
          {
            regex: 'validate',
            message: '验证码长度为4位',
            data: me.validate
          },
          {
            regex: 'password',
            message: '密码不能为空或者密码长度不能少于6位数字',
            data: me.password
          },
          {
            regex: 'conformPassword',
            message: '两次输入密码不一致',
            data: me.conform
          }
        ]
        var status = me.$validation(valData)
        if (status === true) {
          me.validateError = false
          let params = {
            'phone': me.phone,
            'password': me.password,
            'valid': me.validate,
            'email': me.email,
            'reset': 1
          }
          // request.saveHeaders()
          request.post('register', params).then(response => {
            if (response.data.code === '200') {
              this.$router.push({name: 'login'})
            } else {
              this.validateError = true
              this.str = response.data.msg
            }
          }, error => {
            throw new Error('post valid captcha error: ' + error)
          })
        } else {
          this.validateError = true
          this.str = status
        }
      },
      verificaPhone () {
        let valData = [
          {
            regex: 'phone',
            message: '手机号码不能为空或者格式不正确',
            data: this.phone
          }
        ]
        var status = this.$validation(valData)
        if (status === true) {
          this.validateError = false
        } else {
          this.validateError = true
          this.str = status
        }
      },
      phoneVal (val) {
        let me = this
        if (val) {
          me.validateError = false
        }
        me.phone = val
      },
      validateVal (val) {
        let me = this
        if (val) {
          me.validateError = false
        }
        me.validate = val
      },
      passwordVal (val) {
        let me = this
        if (val) {
          me.validateError = false
        }
        me.password = val
      },
      conformVal (val) {
        let me = this
        if (val) {
          me.validateError = false
        }
        me.conform = val
      }
    }
  }
</script>
<style lang="scss">
  .resetpassword-form {
    width: 100%;
    padding: 48px;
    .resetpassword-phone {
      position: relative;
      margin-left: 32px;
      color: #33383e;
      font-size: 40px;
      &:after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 0;
        width: 100%;
        height: 8px;
        background: #00ba91;
      }
    }
    .error-tips {
      height: 80px;
      .valid-error-tips {
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 24px;
        color: #e43112;
        letter-spacing: .44px;
        .error-face {
          margin:0 12px;
        }
      }
    }
    .input-block {
      margin-bottom: 70px;
      .geetest_holder.geetest_wind {
        min-width: 650px !important;
      }
      .captcha-load {
        width: 100%;
        height: 88px;
        align-items: center;
        justify-content: center;
        font-size: 32px;
        color: #00ba91;
      }
    }
    .resetPassWord-submit {
      background: #00ba91;
      border-radius: 8px;
      width: 100%;
      line-height: 72px;
      font-size: 40px;
      color: #ffffff;
      cursor: pointer;
      border: none;
    }
  }
</style>
